package solutions;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 黎鹤舞
 * Date: 2023-12-09
 * Time: 15:04
 */


//给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
// 输入：head = [1,2,3,4,5]
// 输出：[5,4,3,2,1]
// 要求:额外的空间复杂度为O(1)
public class Solution2 {
    public ListNode reverseList(ListNode head) {
        if(head == null) {
            return null;
        }
        if(head.next == null) {
            return head;
        }

        //前驱节点:
        ListNode pre = head;
        //当前节点:
        ListNode cur = head.next;
        //后继节点:
        ListNode curNext = cur.next;
        //同时要把头结点的.next置为空，否则会产生列表回环
        head.next = null;
        while(curNext != null) {
            //把当前节点的next指向前驱节点:
            cur.next = pre;
            pre = cur;
            cur = curNext;
            curNext = curNext.next;
        }
        cur.next = pre;

        return cur;
    }
}
